package com.qyhl.module_home.home.fragment2;


import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.flyco.tablayout.SlidingTabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_home.R;
import com.qyhl.module_home.R2;
import com.qyhl.module_home.common.HomeUrl;
import com.qyhl.module_home.utils.HomeMainViewPager;
import com.qyhl.module_home.utils.view.HomeMessagePop;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.config.AppConfigBean;
import com.qyhl.webtv.commonlib.entity.config.MessageDetailBean;
import com.qyhl.webtv.commonlib.entity.user.MessageUnreadBean;
import com.qyhl.webtv.commonlib.service.CircleService;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.config.HomeThemeColorUtil;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import q.rorbin.badgeview.QBadgeView;

public class HomeFragment2 extends BaseFragment implements HomeContract.HomeView {
    @BindView(R2.id.home2tablayout)
    SlidingTabLayout home2tablayout;
    @BindView(R2.id.home2_vp)
    HomeMainViewPager home2_vp;
    @BindView(R2.id.home2_toolbar)
    RelativeLayout home2_toolbar;
    @BindView(R2.id.home2_toobar_img)
    ImageView home2_toobar_img;
    @BindView(R2.id.search)
    ImageView search;
    @BindView(R2.id.circleMessage)
    ImageView circleMessage;
    @BindView(R2.id.titlelayout)
    LinearLayout titlelayout;
    @BindView(R2.id.home2_toobar_title)
    TextView home2_toobar_title;

//    @BindView(R2.id.circleMessagePoint)
//    ImageView circleMessagePoint;

    private List<AppConfigBean.ThreeMenus> threeMenus;
    private RequestOptions options;//glide配置
    private View view;
    private HomeContract.HomeViewPresenter homeViewPresenter;

    /**
     * 圈子服务
     */
    @Autowired(name = ServicePathConstant.CIRCLE_SERVICE)
    public CircleService circleService;

    private String homeStyle, appLogo, appTitleLogo;
    private boolean isHaveCircle;
    private QBadgeView badgeView;

    public static HomeFragment2 newInstance(String homeStyle, String appLogo, String appTitleLogo, List<AppConfigBean.ThreeMenus> threeMenus, boolean isHaveCircle) {
        HomeFragment2 homeFragment2 = new HomeFragment2();
        homeFragment2.setAppConfig(homeStyle, appLogo, appTitleLogo);
        homeFragment2.setThreeMenus(threeMenus);
        homeFragment2.setIsHaveCircle(isHaveCircle);
        return homeFragment2;
    }

    public HomeFragment2() {
        ARouter.getInstance().inject(this);
    }

    private void setIsHaveCircle(boolean isHaveCircle) {
        this.isHaveCircle = isHaveCircle;
    }

    private void setThreeMenus(List<AppConfigBean.ThreeMenus> threeMenus) {
        this.threeMenus = threeMenus;
    }

    private void setAppConfig(String homeStyle, String appLogo, String appTitleLogo) {
        this.appTitleLogo = appTitleLogo;
        this.homeStyle = homeStyle;
        this.appLogo = appLogo;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //统计数据
            ActionLogUtils.getInstance().onResume(this.getActivity(), ActionConstant.HOME);
        } else {
            GSYVideoManager.releaseAllVideos();
            //统计数据
            ActionLogUtils.getInstance().onPause(this.getActivity(), ActionConstant.HOME);
        }
    }


    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view = inflater.inflate(R.layout.home_fragment_home_fragment2, null);
    }

    @Override
    protected void create() {
        homeViewPresenter = new HomePresenterImpl(this);
        initView();
        homeViewPresenter.setConfig(threeMenus);
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(HomeFragment2.this)
                .statusBarDarkFont(true)
                .titleBar(home2_toolbar)
                .init();
    }

    @Override
    protected void setListener() {
//        ViewCompat.setOnApplyWindowInsetsListener(home2_toolbar, (view, windowInsetsCompat) -> {
//            mTvInsets.setText(getText(getTitle(mTvInsets) + windowInsetsCompat.getSystemWindowInsetTop()));
//            return windowInsetsCompat.consumeSystemWindowInsets();
//        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    private void initView() {
        List<MessageDetailBean> beanList = CommonUtils.getInstance().getTopMessage();
        if (beanList != null && beanList.size() > 0) {
            HomeMessagePop messagePop = new HomeMessagePop(getActivity(), beanList);
            messagePop.setDismissWhenTouchOuside(false);
            messagePop.showPopupWindow();
        }

        //设置大标题
        Typeface fontFace = Typeface.createFromAsset(getContext().getAssets(),
                "fonts/FZXKJW_0.ttf");
        home2_toobar_title.setTypeface(fontFace);
        home2_toobar_title.setTextColor(HomeThemeColorUtil.getCheckColor());
        String appName = CommonUtils.getInstance().getAppName();
        home2_toobar_title.setText(appName);
        //glide配置
        options = new RequestOptions()
                .placeholder(R.drawable.home_fragment_title_bg)
                .error(R.drawable.home_fragment_title_bg)
                .priority(Priority.HIGH);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) titlelayout.getLayoutParams();
        if (!StringUtils.isEmpty(homeStyle)) {
            switch (homeStyle) {
                case "2":
                    Glide.with(getActivity())
                            .load(appLogo)
                            .apply(options)
                            .into(home2_toobar_img);
                    lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
                    break;
                case "3":
                    Glide.with(getActivity())
                            .load(appLogo)
                            .apply(options)
                            .into(home2_toobar_img);
                    break;
                case "4":
                    home2_toobar_img.setVisibility(View.GONE);
                    lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
                    break;
                case "5":
                    home2_toobar_img.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        }
        titlelayout.setLayoutParams(lp);
        Glide.with(getActivity()).load(appTitleLogo).apply(options).into(new CustomViewTarget<RelativeLayout, Drawable>(home2_toolbar) {
            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                home2_toolbar.setBackground(errorDrawable);
            }

            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                home2_toolbar.setBackground(resource);
            }


            @Override
            protected void onResourceCleared(@Nullable Drawable placeholder) {
            }
        });

        //搜索
        search.setOnClickListener(v -> {//路由跳转
            RouterManager.router(ARouterPathConstant.SEARCH);

            ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.SEARCH);
        });

        //消息1
        circleMessage.setOnClickListener(v -> CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                if (isLogin) {
                    RouterManager.router(ARouterPathConstant.NEW_MESSAGE);
                } else {
                    RouterManager.routerLogin(getActivity(), 0);
                }
            }

            @Override
            public void error(String s) {

            }
        }));
    }


    @Override
    public void onDestroy() {
        homeViewPresenter.onDestroy();
        super.onDestroy();
    }


    @Override
    public void onResume() {
        super.onResume();

        EasyHttp.get(HomeUrl.GET_UNREAD_MSG_NUM)
                .params("siteId", CommonUtils.getInstance().getSite() + "")
                .params("devType", "Android")
                .params("sTime", SpfManager.getInstance(getContext()).getString("last_system_time", "0"))
                .params("tTime", SpfManager.getInstance(getContext()).getString("last_tip_time", "0"))
                .params("userName", CommonUtils.getInstance().getUserName())
                .execute(new SimpleCallBack<MessageUnreadBean>() {
                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onSuccess(MessageUnreadBean messageUnreadBean) {
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (messageUnreadBean.getuInteractive() > 0 || messageUnreadBean.getuTips() > 0 || messageUnreadBean.getuSystem() > 0) {
                                        if (badgeView == null) {
                                            badgeView = new QBadgeView(getContext());
                                        }
                                        badgeView.bindTarget(circleMessage).setBadgeNumber(messageUnreadBean.getuSystem() + messageUnreadBean.getuTips() + messageUnreadBean.getuInteractive());
                                    } else {
                                        if (badgeView != null) {
                                            badgeView.hide(false);
                                        }
                                    }
                                } else {
                                    if (badgeView != null) {
                                        badgeView.hide(false);
                                    }
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                    }
                });

        //baidu
        //umeng
        MobclickAgent.onPageStart("首页");
        MobclickAgent.onResume(getContext());
        GSYVideoManager.onResume();

    }

    @Override
    public void setNavigation(ArrayList<Fragment> fragmentList, String[] names) {
        try {
            Class<? extends SlidingTabLayout> aClass = home2tablayout.getClass();
            Field f = aClass.getDeclaredField("mTabPadding");
            f.setAccessible(true);
            f.set(home2tablayout, StringUtils.dip2px(getActivity(), 15));
        } catch (Exception e) {
        }
        home2_vp.setAdapter(new Adaptermm(getActivity().getSupportFragmentManager(), fragmentList, names));
        home2tablayout.setViewPager(home2_vp);
        home2tablayout.setTextSelectColor(HomeThemeColorUtil.getCheckColor());
        home2tablayout.setTextUnselectColor(HomeThemeColorUtil.getTabNormalColor());
        home2tablayout.getTitleView(0).getPaint().setFakeBoldText(true);
    }

    class Adaptermm extends FragmentPagerAdapter {
        private ArrayList<Fragment> fragmentList;
        private String[] names;

        public Adaptermm(FragmentManager fm, ArrayList<Fragment> fragmentList, String[] names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names[position];
        }
    }
}
